import { createGetAPI } from './fetch';
import ModuleItem, { IModuleItem } from './moduleItem';
import * as Util from './util';

interface IModule {
  categoryId: string;
  icon: string;
  name: string;
  type: 'grid' | 'row';
  pageSize: number;
  page: number;
  url: string,
  column?: number;
  pager?: boolean;
  ajax?: boolean;
  callback?: () => void;
}
export default class Module {
  [x: string]: any;
  private config: IModule;
  constructor(ele, config: IModule) {
    this.$ele = $(ele);
    this.config = config;
    this.init();
    this.initEvent();
    this.loadFromServer(this.config.page);
  }

  nextPage(page) {
    if (this.ajax) {
      this.loadFromServer(page);
    } else {
      window.location.href = this.config.url + '?page=' + page
    }
  }

  loadFromServer(page = 1) {
    const api = createGetAPI(`bus/article/articleList.htm`, {
      caetgoryId: this.config.categoryId,
      pageSize: this.config.pageSize,
      page
    });
    const result = api();
    result.then((result) => {
      if (result.body) {
        this.render(result.body.rows);
        this.renderPager(result.body.pager)
      }
    }).catch((error) => {
      console.log(error)
      this.error();
    });
  }
  renderPager(pager: IPage) {
    let html = [];
    if (pager) {
      if (pager.index <= 1) {
        html.push(`<span class="pager-item pager-item--disabled">&lt;&lt;</span>`);
        html.push(`<span class="pager-item pager-item--disabled">&lt;</span>`);
      } else {
        html.push(`<span class="pager-item" data-pager="1">&lt;&lt;</span>`);
        html.push(`<span class="pager-item" data-pager="${pager.index - 1}">&lt;</span>`);
      }
      for (let i = pager.start; i <= pager.end; i++) {
        if (i === pager.index) {
          html.push(`<span class="pager-item pager-item--active">${i}</span>`);
        } else {
          html.push(`<span class="pager-item" data-pager="${i}">${i}</span>`);
        }
      }
      if (pager.index >= pager.totalPage) {
        html.push(`<span class="pager-item pager-item--disabled">&gt;</span>`);
        html.push(`<span class="pager-item pager-item--disabled">&gt;&gt;</span>`);
      } else {
        html.push(`<span class="pager-item" data-pager="${pager.index + 1}">&gt;</span>`);
        html.push(`<span class="pager-item" data-pager="${pager.totalPage}">&gt;&gt;</span>`);
      }
    }
    this.$pager.html(html.join(''));
  }
  render(items: IModuleItem[]) {
    let html = [];
    if (items) {
      items.map((item, index) => {
        item.type = this.config.type;
        item.url = `pageInfo.html?categoryId=${this.config.categoryId}&page=${this.config.page}&id=${item.id}`;
        item.index = index;
        const moduleItem: ModuleItem = new ModuleItem(item);
        html = html.concat(moduleItem.render())
        if (index % this.config.column !== this.config.column - 1) {
          html.push('<div class="module-grid-item-margin">&nbsp;</div>');
        }
      });
    }
    this.$body.html(html.join(''));
    // lazy-loader
    Util.lazyLoad(this.$body);
    if (this.config.callback) {
      this.config.callback();
    }
  }
  renderHeader(): string[] {
    const html = [];
    html.push(`  <div class="module-header">`);
    html.push(`   <span class="web-icon ${this.config.icon}"></span>`);
    html.push(`   <span class="module-title">${this.config.name}</span>`);
    html.push(`  </div>`);
    return html;
  }

  renderFooter(): string[] {
    const html = [];
    html.push(`<div class="module-footer">`);
    if (this.config.pager) {
      html.push(`<div class="pager">`);
      html.push(`  `);
      html.push(`</div>`);
    } else {
      html.push(`  <a class="module-footer-more" href="${this.config.url}">更多&gt;&gt;</a>`);
    }
    html.push(`</div>`);
    return html;
  }

  loading() {
    const html = [];
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<center>加载中...</center>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    this.$body.html(html.join(''));
  }

  error() {
    const html = [];
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<center>加载失败，点击重试！</center>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    this.$body.html(html.join(''));
    this.$body.on('click', () => {
      this.loading();
      this.loadFromServer();
      this.$body.off('click');
    });
  }

  init() {
    let html = [];
    html = html.concat(this.renderHeader());
    if (this.config.type === 'grid') {
      html.push(`  <div class="module-body module-grid">`);
    } else {
      html.push(`  <div class="module-body">`);
    }
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<center>加载中...</center>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`<br/>`);
    html.push(`</div>`);
    html = html.concat(this.renderFooter());
    this.$ele.html(html.join(''));
    this.$body = this.$ele.find('.module-body', this.$ele);
    this.$pager = this.$ele.find('.module-footer .pager', this.$ele);
  }
  initEvent() {
    if (this.config.pager && this.$pager) {
      this.$pager.on('click', (e) => {
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        var $obj = $(obj);
        this.nextPage($obj.attr('data-pager'));
      });
    }
  }

}

///fe/bus/article/articleList.htm